//
//  AppDelegate.swift
//  MyCloudMusic
//
//  Created by jin on 2024/8/18.
//

import UIKit
//import SwiftEventBus
import IQKeyboardManagerSwift

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    
    var isRsumePlay = false
    
    /// 定义一个静态的计算属性
    /// 返回AppDelegate对象实例
    open class var shared:AppDelegate{
        get{
            return UIApplication.shared.delegate as! AppDelegate
        }
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.resignOnTouchOutside = true
        
        if #available(iOS 15.0, *) {
            UITableView.appearance().sectionHeaderTopPadding = 0
        }
        
        initMMKV()
        
        initMedia()
        
        // 设置默认显示界面
        let controller = SplashController()
        window = UIWindow(frame: UIScreen.main.bounds)
        window!.rootViewController = controller
        window!.makeKeyAndVisible()
        
        return true
    }
    
    func initMMKV() {
        MMKV.initialize(rootDir: nil)
    }

    ///跳转到引导页
    func toGuide(){
        let r = GuideController()
        setRootViewController(r)
    }
    
    ///跳转到首页
    func toMain(){
        let r = UINavigationController()
        r.viewControllers = [MainController()]
        setRootViewController(r)
    }
    
    func toAd() {
        let r = AdController()
        setRootViewController(r)
    }
    
    ///跳转到登录页
    func toLogin(){
        toMain()
        
        //然后发送一个跳转到登录界面的通知，在发现界面处理
        DispatchQueue.main.async {
            NotificationCenter.default.post(name: NSNotification.Name(Constant.EVENT_LOGIN_CLICK), object: nil)
        }
    }
    
    func setRootViewController(_ data:UIViewController){
        window!.rootViewController = data
    }
    
    func logout() {
        logoutSilence()
    }
    
    /// 静默退出
    func logoutSilence() {
        //清除登录相关信息
        PreferenceUtil.logout()

        loginStatusChanged()
    }
    
    func onLogin(_ data:Session) {
        
        if let navigationController = window?.rootViewController as? UINavigationController {
            //关闭登陆相关界面
            let vcs = navigationController.viewControllers
            
            var results:[UIViewController] = []
            for it in vcs {
                if it is LoginController ||
                    it is AccountLoginController ||
                    it is RegisterController ||
                    it is InputUserIdentityController ||
                    it is InputCodeController ||
                    it is SetPasswordController {
                    continue
                }
                
                results.append(it)
            }
            
            navigationController.setViewControllers(results, animated: true)
        }
        
        loginStatusChanged()
    }
    
    func loginStatusChanged() {
        SwiftEventBus.post(Constant.EVELT_LOGIN_STATUS_CHANGED)
    }
}


// MARK: - 媒体会话
// 媒体会话
extension AppDelegate{
    
    /**
     初始化音频会话控制

     就是插入耳机，打电话；可以通过系统播放控制中心控制等功能

     官网文档：https://developer.apple.com/documentation/avfoundation/avaudiosession?language=objc
     */
    func initMedia() {
        //告诉系统，我们要接受远程控制事件
        UIApplication.shared.beginReceivingRemoteControlEvents()
        
        //设置响应者
        becomeFirstResponder()
        
        //监听其他音频中断
        //包括其他软件播放音乐
        //当然播放视频也算
        //拨打电话
        //来电
        NotificationCenter.default.addObserver(self, selector: #selector(onInterruptionChanged(notification:)), name: AVAudioSession.interruptionNotification, object: nil)

        //监听耳机插入和拔掉通知
        NotificationCenter.default.addObserver(self, selector: #selector(onAudioRouteChanged(notification:)), name: AVAudioSession.routeChangeNotification, object: nil)
    }
    
    // MARK: - 远程控制事件
    //表示我们当前这个应用是第一响应者
    override var canBecomeFirstResponder: Bool{
        return true
    }
    
    /// 接收远程控制事件
    /// 可以接收到媒体控制中心的事件
    ///
    /// - Parameter event: <#event description#>
    override func remoteControlReceived(with event: UIEvent?) {
        print("AppDelegate remoteControlReceived:\(event?.type),\(event?.subtype)")
        
        //判断是不是远程控制事件
        if event?.type == UIEvent.EventType.remoteControl {
            //是远程控制事件
            
            //是否有音乐
            if MusicListManager.shared().data == nil {
                //当前播放列表中没有音乐
                return
            }
            
            //判断事件类型
            switch event!.subtype {
            case .remoteControlPlay:
                //点击了播放按钮
                print("AppDelegate play")

                MusicListManager.shared().resume()
            case .remoteControlPause:
                //点击了暂停
                print("AppDelegate pause")

                MusicListManager.shared().pause()
            case .remoteControlNextTrack:
                //下一首
                //双击iPhone有线耳机上的控制按钮
                print("AppDelegate next")

                let song = MusicListManager.shared().next()
                MusicListManager.shared().play(song)
            case .remoteControlPreviousTrack:
                //上一首
                //三击iPhone有线耳机上的控制按钮
                print("AppDelegate previouse")

                let song = MusicListManager.shared().previous()
                MusicListManager.shared().play(song)
            case .remoteControlTogglePlayPause:
                //单击iPhone有线耳机上的控制按钮
                print("AppDelegate toggle play pause")

                //播放或者暂停
                if MusicPlayerManager.shared().isPlaying() {
                    MusicListManager.shared().pause()
                } else {
                    MusicListManager.shared().resume()
                }
            default:
                break
            }
        }
    }
    
    /// 音频输出路径改变了回调
    @objc func onAudioRouteChanged(notification:Notification) {
        let userInfo = notification.userInfo

        print("AppDelegate onAudioRouteChanged:\(userInfo)")

        //获取类型
        let type=userInfo![AVAudioSessionRouteChangeReasonKey] as! Int

        //判断类型
        switch type {
        case kAudioSessionRouteChangeReason_NewDeviceAvailable:
            //新增了设备
            print("AppDelegate onAudioRouteChanged new device available")
        case kAudioSessionRouteChangeReason_OldDeviceUnavailable:
            //移除了设备
            onAudioOuputDeviceUnavailable()

        default:
            break
        }
    }
    
    /// 音频输出设备不可用回调
    /// 例如：现在是输出到耳机，耳机就不可用了
    func onAudioOuputDeviceUnavailable() {
        //这里是子线程
        DispatchQueue.main.async {
            //切换到主线程

            //因为播放管理器中会回调界面
            if PreferenceUtil.isUnplugHeadsetStopMusic(){
                if MusicPlayerManager.shared().isPlaying() {
                    //有音乐正在播放

                    //暂停
                    MusicListManager.shared().pause()
                }
            }
        }
    }
    
    /// 音频中断了
    /// 包括其他软件播放音频
    /// 来电话了；拨打电话等
    @objc func onInterruptionChanged(notification:Notification) {
        print("AppDelegate onInterruptionChanged")
        
        //将三个变量都拆包
        //如果有一个变量拆包失败
        //就直接返回了
        guard let userInfo = notification.userInfo,
            let interruptionTypeRawValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
            let interruptionType = AVAudioSession.InterruptionType(rawValue: interruptionTypeRawValue) else {
            return
        }
        
        switch interruptionType {
        case .began:
            //中断事件开始
            //例如：播放电话，或者接听电话

            if MusicPlayerManager.shared().isPlaying() {
                //音乐在播放

                //暂停
                MusicListManager.shared().pause()

                //自动恢复播放
                isRsumePlay = true
            }
        case .ended:
            //中断事件结束了
            //例如：挂断电话
            print("AppDelegate onInterruptionChanged ended")

            if isRsumePlay {
                //自动恢复播放
                MusicListManager.shared().resume()

                //清除自动播放标记
                isRsumePlay = false
            }
        default:
            break
        }
    }
}

